/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.taglibs.input;

import com.codemagi.util.Utils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;
import org.apache.log4j.Logger;

/**
 *  This class implements the &lt;input:field&gt; tag, which presents an
 *  HTML DIV tag with the field contents, backed by a &lt;hidden&gt; form
 *  element to enable persistence between form submits. 
 *
 *  @version 1.0                                                                                           
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class Field extends Input {

    Logger log = Logger.getLogger(this.getClass());

    public int doStartTag() throws JspException {
	try {
            // sanity check
            if (name == null || name.equals(""))
                throw new JspTagException("invalid null or empty 'name'");

	    // get what we need from the page
	    ServletRequest req = pageContext.getRequest();
	    JspWriter out      = pageContext.getOut();

	    StringBuffer divTag    = new StringBuffer(100);
	    StringBuffer hiddenTag = new StringBuffer(100);

	    //we need to have an ID
	    if (Utils.isEmpty(id)) id = Util.quote(name);

	    // start building up the tag
	    out.println();

	    divTag.append("<div ");
	    divTag.append("    name=\"field_" + Util.quote(name) + "_field\"");
	    divTag.append("    id=\"field_" + id + "_field\"");
	    divTag.append(">");

	    hiddenTag.append("<input ");
	    hiddenTag.append("    type=\"hidden\"");
	    hiddenTag.append("    name=\"" + Util.quote(name) + "\"");
	    hiddenTag.append("    id=\"" + id + "\"");

	    /*
	     * print out the value from the request if it's there, or
	     * use the default value if it's not
	     */
	    String requestValue = getParameter(name, (HttpServletRequest)req);

            if ( override ) {
		log.debug("override. dVal: " + dVal);

                divTag.append( dVal );
                hiddenTag.append("    value=\"" + Util.quote(dVal) + "\"");
            } else if ( !Utils.isEmpty(requestValue) ) {
		log.debug("request. requestValue: " + requestValue);

                divTag.append( requestValue );
		hiddenTag.append("    value=\"" + Util.quote(requestValue) + "\"");
	    } else if (dVal != null) {
		log.debug("default. dVal: " + dVal);

                divTag.append( Util.quote(dVal) );
		hiddenTag.append("    value=\"" + Util.quote(dVal) + "\"");
	    }

	    // end the tags
	    divTag.append("</div>");
	    hiddenTag.append("/>");

	    out.println( divTag.toString() );
	    out.println( hiddenTag.toString() );

	    // add reference to javascript code
	    if (!"true".equals(pageContext.getAttribute("cminput.field.imported"))) {

		out.println("<script type=\"text/javascript\">");
		out.println("    function updateField(targetId, newValue) { ");

		out.println("        var theDiv = document.getElementById('field_' + targetId + '_field'); ");
		out.println("        theDiv.innerHTML = newValue; ");

		out.println("        var hidden = document.getElementById( targetId ); ");
		out.println("        hidden.value = newValue; ");
		out.println("    } ");
		out.println("</script>");

		//flag that the reference code has been added 
		pageContext.setAttribute("cminput.field.imported","true");
	    }

	} catch (Exception ex) {
	    throw new JspTagException(ex.getMessage());
	}
	return SKIP_BODY;
    }
}
